package com.example.logindemo.config;

import com.example.logindemo.entity.User;
import com.example.logindemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 应用启动时初始化默认用户
 */
@Component
public class UserInitializer implements ApplicationRunner {

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    @Transactional
    public void run(ApplicationArguments args) throws Exception {
        // 检查是否存在管理员用户，如果不存在则创建
        User adminUser = userService.getUserByUsername("admin");
        if (adminUser == null) {
            User newAdmin = new User();
            newAdmin.setUsername("admin");
            newAdmin.setPassword(passwordEncoder.encode("admin123"));
            newAdmin.setEmail("admin@example.com");
            userService.createUser(newAdmin);
            System.out.println("默认管理员用户创建成功: admin / admin123");
        }

        // 创建测试用户
        User testUser = userService.getUserByUsername("testadmin");
        if (testUser == null) {
            User newTestUser = new User();
            newTestUser.setUsername("testadmin");
            newTestUser.setPassword(passwordEncoder.encode("123456"));
            newTestUser.setEmail("test@example.com");
            userService.createUser(newTestUser);
            System.out.println("测试用户创建成功: testadmin / 123456");
        }
    }
}